class TopicsController < ApplicationController
  before_filter :load_resources, :except => [:index, :search]

  def show
    @topic = Topic.find(
      params[:id],
      :select => 'topics.title, topics.user_id',
      :include => [:posts[:content_html, :created_at, :updated_at] => :user[:login]],
      :order => 'posts.created_at ASC'
    )
    @title = @topic.title
    @topic.hit! if @topic.user_id != current_user.id
    
    respond_to do |format|
      format.html { render }
      format.xml  { render :xml => @topic.to_xml(:include => [:posts]) }
    end
  rescue ActiveRecord::RecordNotFound
    flash[:error] = _('Topic not found')
    redirect_back_or(forum_path(params[:forum_id]))
  end
  
  def edit
    @topic = @forum.topics.find(params[:id])
  end
  
  def create
    @topic = @forum.topics.build(params[:topic].except(:user_id))
    @topic.user_id = current_user.id
    
    respond_to do |format|
      if @topic.save
        flash[:notice] = _('Topic was successfully created')
        format.html { redirect_to forum_topic_path(@forum, @topic) }
        format.xml  { head :created, :location => forum_topic_path(@forum, @topic) }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @topic.errors.to_xml }
      end
    end
  end
  
  def update
    @topic = @forum.topics.find(params[:id])
    new_attributes = params[:topic].except(:user_id)
    new_attributes.merge(:updated_by => current_user.id) if current_user.id != @topic.user_id
    
    respond_to do |format|
      if @topic.update_attributes(new_attributes)
        flash[:notice] = _('Topic was successfully updated')
        format.html { redirect_to forum_topic_path(@forum, @topic) }
        format.xml  { head :ok, :location => forum_topic_path(@forum, @topic) }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @topic.errors.to_xml }
      end
    end
  end
  
  private
  def load_resources
    @forum = Forum.find(params[:forum_id], :select => 'forums.id, forums.name, forums.permalink', :include => :category[:name])
    @category = @forum.category
  end
end
